package productcallback;

import com.rabbitmq.client.Channel;
import common.ContantsConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;

import java.io.IOException;

/**
 * 消费者接受后setMandatory，通知发布者自己已经确认。消费者得到确认通知
 */
public class Consumer {

    public static void main(String[] args) throws IOException {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(ContantsConfig.MQ_HOST);
        connectionFactory.setUsername(ContantsConfig.USER);
        connectionFactory.setPassword(ContantsConfig.PASSWORD);

        /**
         * 开启确认模式(消费者需要把publisherReturns设置为true)
         */
        connectionFactory.setPublisherReturns(true);


        Connection connection = connectionFactory.createConnection();


        //创建一个新的通道, 不支持事务, true表示支持
        Channel channel = connection.createChannel(false);


        /**
         * 声明队列
         */
        channel.queueDeclare("hello-queue", true, true, false, null);


        /**
         * 将队列和交换器绑定
         */
        channel.queueBind("hello-queue", "hello-exchange", "hola");


        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setQueue("hello-queue");


        /**
         * 回复发布者(mandatory要设置成true)  委托的，务必
         */
        template.setMandatory(true);
        template.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                System.out.println(message);
                System.out.println(replyCode);
                System.out.println(replyText);
                System.out.println(exchange);
                System.out.println(routingKey);
            }
        });



        /**
         * 使用监听异步接收消息
         */
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setQueueNames("hello-queue");
        container.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                System.out.println(message);
            }
        });
        container.start();
    }
}
